package com.kreedx.writer;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

@SpringBootApplication
@Slf4j
public class WriterApplication implements ApplicationRunner, ApplicationListener<ContextClosedEvent> {
    public static void main(String[] args) {
        SpringApplication.run(WriterApplication.class, args);
    }


    StringBuilder stringBuilder = new StringBuilder();

    @Override
    public void run(ApplicationArguments args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        File dir = new File("./txt/");
        if (!dir.exists()) dir.mkdirs();
        File file = new File(dir.getPath() + File.separator + "2.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file, true);
        FileInputStream fileInputStream = new FileInputStream(file);
        log.info("nums:{}", fileInputStream.available() / 4);

        Runtime.getRuntime().exec(new String[]{"cmd", "/c", "cls"});

        while (!Thread.interrupted()) {
            if (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                stringBuilder.append(line).append("\n");
                fileOutputStream.write(line.getBytes(StandardCharsets.UTF_8));
                fileOutputStream.write("\n".getBytes(StandardCharsets.UTF_8));
            }
        }

        fileOutputStream.close();
    }

    @SneakyThrows
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {

    }
}
